#include "pch.h"
#include "shaders.h"
#include "ErrorCodes.h"
#include "IOHelper.h"

using namespace Platform;
using namespace Windows::Foundation;

using namespace concurrency;

using namespace DXBase;
using namespace DXBase::D3D;


VertexShader::VertexShader()
{
	watcher.Target = this;
}
void VertexShader::LoadShaderFile(DXBase::D3D::VertexLayout^ layout, Platform::String^ file)
{
	mLayout = nullptr;
	shader_bytecode = nullptr;
	ClearDXData();
	if (file && layout) 
	{
		shader_bytecode = IOHelper::ReadFile(file);
		mLayout = layout;
	}
}
void VertexShader::LoadDXData()
{
	if (mBasicVertexShader) // done already
		return;
	if (!shader_bytecode)
		return;
	if (!Context)
		throw ExHelper::CreateException(ErrorCodes::ContextNotSet);

	std::vector<D3D11_INPUT_ELEMENT_DESC> layout_elems;
	std::vector<char> semanticNameBuffer;
	mLayout->Fill(layout_elems, semanticNameBuffer);

	HR2Ex(Context->m_d3dDevice->CreateVertexShader(shader_bytecode->Data, shader_bytecode->Length, nullptr, mBasicVertexShader.GetAddressOf()));
	HR2Ex(Context->m_d3dDevice->CreateInputLayout(&layout_elems[0], (UINT)layout_elems.size(), shader_bytecode->Data, shader_bytecode->Length, mBasicInputLayout.GetAddressOf()));
}


PixelShader::PixelShader()
{
	watcher.Target = this;
}
void PixelShader::LoadShaderFile(Platform::String^ file)
{
	shader_bytecode = nullptr;
	ClearDXData();
	if (file) 
	{
		shader_bytecode = IOHelper::ReadFile(file);
	}
}
void PixelShader::LoadDXData()
{
	if (mBasicPixelShader) // done already
		return;
	if (!shader_bytecode)
		return;
	if (!Context)
		throw ExHelper::CreateException(ErrorCodes::ContextNotSet);

	HR2Ex(Context->m_d3dDevice->CreatePixelShader(shader_bytecode->Data, shader_bytecode->Length, nullptr, mBasicPixelShader.GetAddressOf()));
}
